import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_swiper_view/flutter_swiper_view.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:wan_android_flutter/common_ui/loading.dart';
import 'package:wan_android_flutter/common_ui/web/webview_page.dart';
import 'package:wan_android_flutter/common_ui/web/webview_widget.dart';
import 'package:wan_android_flutter/pages/home/home_vm.dart';
import 'package:wan_android_flutter/route/RouteUtils.dart';
import 'package:wan_android_flutter/route/routes.dart';
import '../../common_ui/smart_refresh/smart_refresh_widget.dart';
import '../../repository/datas/home_list_data.dart';

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<StatefulWidget> createState() {
    return _HomePageState();
  }
}

class _HomePageState extends State<HomePage> {
  HomeViewModel viewModel = HomeViewModel();
  RefreshController refreshController = RefreshController();

  @override
  void initState() {
    super.initState();
    Loading.showLoading();
    viewModel.getBanner();
    //viewModel.initListData(false);
    refreshOrLoad(false);
  }

  void refreshOrLoad(bool loadMore) {
    viewModel.initListData(loadMore, callback: (loadMore) {
      if (loadMore) {
        refreshController.loadComplete();
      } else {
        refreshController.refreshCompleted();
      }
      Loading.dismissAll();
    });
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<HomeViewModel>(
      create: (context) {
        return viewModel;
      },
      child: Scaffold(
        body: SafeArea(
          child: SmartRefreshWidget(
            controller: refreshController,
            onLoading: () {
              //上拉加载回调
              refreshOrLoad(true);
            },
            onRefresh: () {
              //下拉刷新回调
              refreshOrLoad(false);
            },
            child: SingleChildScrollView(
              child: Column(
                children: [_banner(), _homeListView()],
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget _banner() {
    return Consumer<HomeViewModel>(builder: (context, vm, child) {
      print("_banner 刷新");
      return SizedBox(
          width: double.infinity,
          height: 150.h,
          child: Swiper(
            indicatorLayout: PageIndicatorLayout.NONE,
            autoplay: true,
            pagination: const SwiperPagination(),
            control: const SwiperControl(),
            itemCount: vm.bannerList?.length ?? 0,
            itemBuilder: (context, index) {
              return GestureDetector(
                onTap: () {
                  //跳转到网页
                  RouteUtils.push(
                      context,
                      WebViewPage(
                        loadResource: vm.bannerList?[index].url ?? "",
                        webViewType: WebViewType.URL,
                        showTitle: true,
                        title: vm.bannerList?[index].title,
                      ));
                },
                child: Container(
                  height: 150.h,
                  color: Colors.lightBlue,
                  child: Image.network(
                    vm.bannerList?[index].imagePath ?? "",
                    fit: BoxFit.fill,
                  ), //Image.network 获取网络数据图片
                ),
              );
            },
          ));
    });
  }

  Widget _homeListView() {
    print("_homeListView 刷新");
    return Consumer<HomeViewModel>(builder: (context, vm, child) {
      return ListView.builder(
        shrinkWrap: true,
        physics: const NeverScrollableScrollPhysics(),
        itemBuilder: (context, index) {
          return _listItemView(vm.listData?[index], index);
        },
        itemCount: vm.listData?.length ?? 0,
      );
    });
  }

  Widget _listItemView(HomeListItemData? item, int index) {
    //InkWell() 点击水波纹效果

    var name;
    if (item?.author?.isNotEmpty == true) {
      name = item?.author ?? "";
    } else {
      name = item?.shareUser ?? "";
    }

    return GestureDetector(
        onTap: () {
          //跳转到网页
          RouteUtils.push(
              context,
              WebViewPage(
                loadResource: item?.link ?? "",
                webViewType: WebViewType.URL,
                showTitle: true,
                title: item?.title,
              ));
        },
        child: Container(
          margin:
              EdgeInsets.only(top: 5.h, bottom: 5.h, left: 10.w, right: 10.w),
          padding:
              EdgeInsets.only(top: 15.h, bottom: 15.h, left: 10.w, right: 10.w),
          decoration: BoxDecoration(
              border: Border.all(color: Colors.black12, width: 0.5.r),
              borderRadius: BorderRadius.all(Radius.circular(6.r))),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  ClipRRect(
                      borderRadius: BorderRadius.all(Radius.circular(15.r)),
                      child: Image.network(
                        "https://picsum.photos/200",
                        width: 30.w,
                        height: 30.h,
                      )),
                  SizedBox(width: 5.r),
                  Text(
                    name,
                    style: const TextStyle(color: Colors.black),
                  ),
                  const Expanded(child: SizedBox()),
                  Text(item?.niceShareDate ?? "",
                      style: TextStyle(color: Colors.black, fontSize: 12.sp)),
                  SizedBox(width: 5.r),
                  //0=非置顶数据 1=置顶数据
                  (item?.type?.toInt() == 1)
                      ? const Text("置顶",
                          style: TextStyle(
                              color: Colors.blue, fontWeight: FontWeight.bold))
                      : const SizedBox(),
                ],
              ),
              SizedBox(
                height: 5.h,
              ),
              Text(item?.title ?? "",
                  style: TextStyle(color: Colors.black, fontSize: 14.sp)),
              Row(
                children: [
                  Text(
                    item?.chapterName ?? "",
                    style: TextStyle(color: Colors.green, fontSize: 12.sp),
                  ),
                  const Expanded(child: SizedBox()),
                  GestureDetector(
                    onTap: () {
                      if (item?.collect == true) {
                        viewModel.unCollect("${item?.id}", index);
                      } else {
                        viewModel.collect("${item?.id}", index);
                      }
                    },
                    child: Image.asset(
                      item?.collect == true
                          ? "assets/images/img_collect.png"
                          : "assets/images/img_collect_grey.png",
                      width: 30.r,
                      height: 30.r,
                    ),
                  )
                ],
              )
            ],
          ),
        ));
  }
}
